<!--
 * @author liganghao
 -->
<template>
  <div id="organmanage">
    <div class="btn-container">
      <div class="btn-container-title">
        <span>组织管理</span>
        <span v-if="breadList.length > 0">,当前选择</span>
        <span
          v-if="breadList.length"
          class="btn-container-title-select"
          :title="breadList.join('>')"
        >{{ breadList.join('>') }}</span>
      </div>
      <div class="btn-container-btns">
        <el-button
          v-permission="'organmanageInsert'"
          class="filter-item"
          style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;"
          @click="handleCreateFirst"
        >新增一级组织</el-button>
        <template v-if="temp.parentId != ''">
          <el-button
            v-permission="'organmanageInsertLeaf'"
            class="filter-item"
            style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;"
            @click="handleCreate"
          >新增下级</el-button>
          <el-button
            v-permission="'organmanageDelete'"
            class="filter-item"
            style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;"
            @click="handleDelete"
          >删除</el-button>
          <el-button
            v-if="parentId"
            v-permission="'organmanageAdministrator'"
            class="filter-item"
            style="padding: 10px 30px;margin-left: 10px;margin-bottom: 0;"
            @click="handleSetAdmin"
          >设置管理员</el-button>
        </template>
      </div>
    </div>
    <el-container class="enterpriseinfo">
      <el-aside width="350px" class="leftWrap">
        <div class="search-tree-wrap">
          <el-input
            v-model.trim="treeName"
            style="width:240px"
            placeholder="组织名称搜索"
            class="search-input"
            clearable
            @clear="clearSearchTree"
          />
          <el-button class="filter-item tree-filter" type="primary" @click="handleFilterTree">搜索</el-button>
        </div>
        <el-tree
          v-if="!issearchtree"
          ref="qytree"
          key="lodTree"
          v-loading="treeLoading"
          :data="treeData"
          :props="defaultProps"
          :expand-on-click-node="false"
          class="dictTree"
          highlight-current
          node-key="id"
          :filter-node-method="filterNode"
          :load="loadtree"
          lazy
          @node-click="handleUpdate"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span
              :class="['tag', data.orgType==='JGLX01'?'gh':(data.orgType==='JGLX02'?'qy':'')]"
            >{{ data.orgTypeValue }}</span>
          </span>
        </el-tree>
        <el-tree
          v-if="issearchtree"
          ref="qytree"
          key="newTree"
          v-loading="treeLoading"
          :data="treeData"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          class="dictTree"
          default-expand-all
          highlight-current
          @node-click="handleUpdate"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span
              :class="['tag', data.orgType==='JGLX01'?'gh':(data.orgType==='JGLX02'?'qy':'')]"
            >{{ data.orgTypeValue }}</span>
          </span>
        </el-tree>
      </el-aside>
      <el-main class="user-main">
        <div v-if="!isShow" class="ts-con">
          <div class="ts">
            <i class="el-icon-info" />
            <span v-html="showMsg" />
          </div>
        </div>
        <div v-else id="enterpriseinfo-container">
          <el-form
            ref="dataForm"
            v-loading="submitloading"
            :model="temp"
            :rules="rules"
            class="dataForm"
            label-position="right"
            label-width="150px"
            style="width: 400px;overflow: auto;"
          >
            <el-form-item v-if="higherLevel" label="上级组织">
              <el-input v-model.trim="higherLevel" disabled="disabled" />
            </el-form-item>
            <el-form-item label="组织代码" prop="orgCode">
              <el-input v-model.trim="temp.orgCode" placeholder="请输入组织代码" />
            </el-form-item>
            <el-form-item label="组织名称" prop="orgName">
              <el-input v-model.trim="temp.orgName" placeholder="请输入组织名称" />
            </el-form-item>
            <el-form-item label="社会统一信用代码" prop="orgCodeCertificate">
              <el-input v-model.trim="temp.orgCodeCertificate" placeholder="请输入社会统一信用代码" />
            </el-form-item>
            <el-form-item label="类型" prop="orgType">
              <el-radio-group v-model="temp.orgType">
                <el-radio
                  v-for="v in dict.JGLX"
                  :key="v.dictValue"
                  :label="v.dictValue"
                >{{ v.dictName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="temp.orgType=='JGLX02'" label="上级企业" prop="enterpriseId">
              <el-select
                v-model.trim="temp.enterpriseIdValue"
                style="width: 100%;"
                filterable
                remote
                reserve-keyword
                placeholder="请输入上级企业"
                :remote-method="getComList"
                :loading="comLoading"
              >
                <el-option
                  v-for="item in comOption"
                  :key="item.id"
                  :label="item.orgName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="temp.sort" placeholder="请输入序号" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio
                  v-for="v in dict.ZT"
                  :key="v.dictValue"
                  :label="v.dictValue"
                >{{ v.dictName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button style="padding: 8px 30px;" @click="isShow=false">取消</el-button>
              <el-button
                v-permission="'organmanageUpdate'"
                style="padding: 8px 30px;"
                type="primary"
                @click="dialogStatus==='create'?createData():updateData()"
              >确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="'设置管理员'"
      :visible.sync="dialogSetAdminVisible"
      center
      width="1000px"
    >
      <set-admin ref="setAdmin" :object-id="parentId" :open-state="dialogSetAdminVisible" />
      <div slot="footer" class="dialog-footer">
        <!-- <el-button style="padding: 8px 30px;" type="primary" @click="sure()">确定</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { specialText } from '@/utils/validate'
import { getDictByCode, createFirst, insert, update, del, get, getComTreeSync, getSelectCompany, roleListByName } from '@/views/organmanage/api/index'
import { mapGetters } from 'vuex'
import SetAdmin from '@/views/organmanage/components/setadmin'
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui

export default {
  name: 'Organmanage',
  components: { SetAdmin },
  directives: { permission, elDragDialog },
  data() {
    return {
      treeLoading: false,
      submitloading: false,
      comLoading: false,
      isShow: false,
      comOption: [],
      showMsg: '单击左侧菜单项进行维护',
      issearchtree: false,
      treeData: [],
      tradeList: [], // 行业列表
      defaultProps: {
        children: 'list',
        label: 'orgName'
      },
      treeName: '',
      dialogStatus: '',
      parentId: '',
      parentNme: '',
      refreshParentId: '',
      temp: {
        parentId: '',
        orgCode: '',
        orgCodeCertificate: '',
        orgType: 'JGLX01', // 默认工会
        enterpriseId: '',
        enterpriseIdValue: '',
        status: 'ZT01', // 默认开启
        sort: '',
        orgName: '',
        id: ''
      },
      rules: {
        orgCode: [{ required: true, message: '请输入组织代码', trigger: 'blur' }, { validator: specialText, trigger: 'blur' }],
        orgName: [{ required: true, message: '请输入组织名称', trigger: 'blur' }, { validator: specialText, trigger: 'blur' }],
        orgCodeCertificate: [{ required: true, message: '请输入社会统一信用代码', trigger: 'blur' }],
        sort: [
          {
            validator: (rule, value, callback) => {
              if (value !== '') {
                if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
                  callback(new Error('请填写大于0的数字'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      higherLevel: '',
      breadList: [],
      superIdType: 0,
      dialogSetAdminVisible: false,
      dict: {
        JGLX: [], // 组织类型
        ZT: [] // 状态
      },
      rySeleteData: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.getTreeData()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    refreshNodeBy(id) {
      this.$nextTick(() => {
        const node = this.$refs.qytree.getNode(id) // 通过节点id找到对应树节点对象
        console.log(node)
        node.loaded = false
        node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
      })
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
        }).catch(error => {
          reject(error)
        })
      })
    },
    sure() {
      this.dialogSetAdminVisible = false
    },
    /**
     * 设置管理员
     */
    handleSetAdmin() {
      if (this.parentId) {
        this.dialogSetAdminVisible = true
        this.$nextTick(() => {
          this.$refs.setAdmin.handleReset()
        })
      } else {
        this.$message({
          message: '请先选择要设置的组织！',
          type: 'warning'
        })
      }
    },
    /**
     * 获取上级企业列表
     */
    getComList(query) {
      if (query !== '') {
        this.comLoading = true
        return new Promise((resolve, reject) => {
          getSelectCompany({ orgName: query, orgType: this.temp.orgType, id: this.parentId }).then(response => {
            this.comLoading = false
            this.comOption = response.data.data
          }).catch(error => {
            reject(error)
            this.comOption = []
            this.comLoading = false
          })
        })
      } else {
        this.comOption = []
      }
    },
    /**
     * 清空搜索企业
     */
    clearSearchTree() {
      this.treeName = ''
      this.issearchtree = false
      this.getTreeData()
    },
    /**
     * 按企业名称查询
     */
    handleFilterTree() {
      // this.$refs.qytree.filter(this.treeName)
      if (this.treeName === '') {
        this.issearchtree = false
        this.getTreeData()
      } else {
        this.issearchtree = true
        this.treeLoading = true
        return new Promise((resolve, reject) => {
          roleListByName({ orgName: this.treeName }).then(response => {
            this.treeLoading = false
            this.treeData = response.data.data
          }).catch(error => {
            reject(error)
            this.issearchtree = false
            this.treeLoading = false
          })
        })
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.orgName.indexOf(value) !== -1
    },
    getTreeData(id) {
      this.treeLoading = true
      return new Promise((resolve, reject) => {
        getComTreeSync(id).then(response => {
          this.treeLoading = false
          this.treeData = response.data.data
        }).catch(error => {
          reject(error)
          this.treeLoading = false
        })
      })
    },
    loadtree(node, resolve) {
      this.treeloading = true
      if (node.data.canLookDown === 1) {
        this.$message({
          message: '您没有查看下级企业的数据权限，请联系上级管理员开放权限！',
          type: 'error'
        })
        return
      }
      if (node.level !== 0) {
        getComTreeSync(node.data.id).then(res => {
          this.treeloading = false
          resolve(res.data.data)
        }).catch(res => {
          this.treeloading = false
          resolve([])
        })
      }
    },
    resetTemp() {
      this.temp = {
        parentId: '',
        orgCode: '',
        orgCodeCertificate: '',
        orgType: 'JGLX01', // 默认工会
        enterpriseId: '',
        status: 'ZT01', // 默认开启
        sort: '',
        orgName: '',
        id: ''
      }
      this.comOption = []
    },
    handleCreateFirst() {
      this.dialogStatus = 'create'
      this.higherLevel = ''
      this.isShow = true
      this.resetTemp()
      this.$nextTick(() => {
        this.temp.parentId = -1
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.isShow = true
      this.resetTemp()
      this.$nextTick(() => {
        this.higherLevel = this.parentNme
        this.temp.parentId = this.parentId
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 获取当前树节点和其父级节点
     */
    getTreeNode(Node) {
      if (Node) {
        if (Node.label !== undefined) {
          this.breadList.unshift(Node.label) // 在数组头部添加元素
          this.getTreeNode(Node.parent) // 递归
        }
      }
    },
    handleUpdate(data, Node) {
      this.breadList = []
      this.getTreeNode(Node)
      this.parentId = data.id
      this.parentNme = data.orgName
      this.higherLevel = Node.parent.label
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(data.id).then((res) => {
          loading.close()
          this.temp = {
            parentId: res.data.data.parentId,
            orgCode: res.data.data.orgCode,
            orgCodeCertificate: res.data.data.orgCodeCertificate,
            orgType: res.data.data.orgType,
            enterpriseId: res.data.data.enterpriseId,
            enterpriseIdValue: res.data.data.enterpriseIdValue,
            status: res.data.data.status,
            sort: res.data.data.sort,
            orgName: res.data.data.orgName,
            id: res.data.data.id
          }
          this.refreshParentId = res.data.data.parentId || -1// 刷新父级id
          this.dialogStatus = 'update'
          this.isShow = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }).catch(error => {
          reject(error)
          loading.close()
        })
      })
    },
    handleDelete() {
      if (this.parentId) {
        this.delete(this.parentId)
      } else {
        this.$message({
          message: '请选择删除的项！',
          type: 'warning'
        })
      }
    },
    delete(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return new Promise((resolve, reject) => {
          del(ids).then((res) => {
            loading.close()
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
            if (this.refreshParentId === 1 || this.refreshParentId === -1) {
              this.getTreeData()
            } else {
              this.refreshNodeBy(this.refreshParentId)
              this.refreshParentId = ''
            }
            this.isShow = false
          }).catch(error => {
            reject(error)
            loading.close()
          })
        })
      }).catch(() => {

      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          this.getCompNameByCompId()
          if (this.temp.parentId == -1) {
            return new Promise((resolve, reject) => {
              createFirst(this.temp).then((res) => {
                this.isShow = false
                loading.close()
                this.$message({
                  message: '创建成功！',
                  type: 'success'
                })
                this.handleFilterTree()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return new Promise((resolve, reject) => {
              insert(this.temp).then((res) => {
                this.isShow = false
                this.refreshNodeBy(res.data.data.parentId)
                loading.close()
                this.$message({
                  message: '创建成功！',
                  type: 'success'
                })
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          }
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          this.getCompNameByCompId()
          return new Promise((resolve, reject) => {
            update(this.temp).then((res) => {
              this.isShow = false
              loading.close()
              this.$message({
                message: '编辑成功！',
                type: 'success'
              })
              console.log(this.refreshParentId)
              this.refreshNodeBy(this.refreshParentId)
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    updateTreeChildren(data) {
      const node = this.$refs.qytree.getNode(this.temp.parentId)
      if (!node) return
      const childNodes = node.childNodes
      for (let i = childNodes.length - 1; i >= 0; i--) {
        const child = childNodes[i]
        this.$refs.qytree.remove(child.data)
      }
      for (let i = 0, j = data.length; i < j; i++) {
        const child = data[i]
        this.$refs.qytree.append(child, node.data)
      }
    },
    getCompNameByCompId() {
      const _this = this
      if (this.comOption.length > 0) {
        this.comOption.forEach(item => {
          console.log(item)
          if (_this.temp.enterpriseIdValue === item.id) {
            _this.temp.enterpriseId = item.id
            _this.temp.enterpriseIdValue = item.orgName
            return
          }
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
$dark_gray: #bfced6;
$mainColor: #18a5fd;
#organmanage {
  padding: 10px;
  .enterpriseinfo {
    height: calc(100vh - 127px);
    padding: 0px;
    .leftWrap {
      background: #fff;
      margin-right: 10px;
      padding: 10px;
      .search-tree-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .tree-filter {
          padding: 10px 18px;
        }
      }
      .el-tree-node__content {
        margin-top: 10px;
      }
      .tag {
        font-size: 12px;
        border-radius: 4px;
        padding: 2px 4px;
        color: #fff;
        &.gh {
          color: #ff7474;
          border: 1px solid #ff7474;
        }
        &.qy {
          color: #2fbcfb;
          border: 1px solid #2fbcfb;
        }
        &.bm {
          color: #ffa11c;
          border: 1px solid #ffa11c;
        }
      }
      .el-tree-node__expand-icon.expanded {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      .el-icon-caret-right:before {
        content: "\E7A0";
        font-size: 14px;
      }
      .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
        content: "\E7A2";
        font-size: 14px;
      }
    }
    .user-main {
      padding: 10px;
      position: relative;
      background-color: #fff;
      .ts-con {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        background: white;
        .ts {
          line-height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-top: -15px;
          margin-left: -110px;
          width: 210px;
          text-align: center;
          background: white;
          border-radius: 2px;
          box-shadow: 1px 1px 5px #e0dbdb;
          font-size: 14px;
          font-family: Microsoft Yahei In-Bold, Microsoft Yahei,
            Apple LiGothic Medium;
          color: #222222;
        }
      }
      &::-webkit-scrollbar {
        display: none;
      }
    }
  }
  .sysconfig-search {
    background-color: #fff;
    padding: 5px 10px;
    margin-bottom: 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;
      &_login {
        font-size: 10px;
      }
    }
    .search-input {
      width: 78%;
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }
  .btn-container {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color: rgba(51, 51, 51, 1);
      span {
        overflow: hidden;
        display: inline-block;
      }
      .btn-container-title-select {
        width: 430px;
        text-overflow: ellipsis;
        white-space: nowrap;
        @include font-color($mainColor);
      }
    }
  }
}
</style>
